package com.xbibo.autoconfigure.dal.utils;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.BeanUtilsBean2;
import org.apache.commons.beanutils.ContextClassLoaderLocal;
import org.apache.commons.beanutils.converters.DateConverter;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

/**
 * Created by riverzu on 2017/9/24.
 */
public class BeanUtils2 extends BeanUtils {

    private static final ContextClassLoaderLocal<BeanUtilsBean2>
            BEANS2_BY_CLASSLOADER = new ContextClassLoaderLocal<BeanUtilsBean2>() {
        @Override
        protected BeanUtilsBean2 initialValue() {
            BeanUtilsBean2 beanUtilsBean2 = new BeanUtilsBean2();
            //设置日期转换器
            DateConverter dateConverter = new DateConverter();
            dateConverter.setPattern("yyyy-MM-dd HH:mm:ss");
            beanUtilsBean2.getConvertUtils().register(dateConverter, Date.class);
            return beanUtilsBean2;
        }
    };

    public static BeanUtilsBean getInstance() {
        return BEANS2_BY_CLASSLOADER.get();
    }

    public static void populate(final Object bean, final Map<String, ? extends Object> properties)
            throws IllegalAccessException, InvocationTargetException {
        getInstance().populate(bean, properties);
    }

    public static Map<String, String> describe(final Object bean)
            throws IllegalAccessException, InvocationTargetException,
            NoSuchMethodException {
        return getInstance().describe(bean);
    }
}
